package com.android.fragmentdemo.leanback
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.ItemBridgeAdapter
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.android.fragmentdemo.R
import com.hengfoxwolf.commonbase.base.BaseActivity
import com.android.fragmentdemo.databeans.DataFactoryIp
import com.android.fragmentdemo.databinding.ActivityVgvuseVactivityBinding
import java.lang.ref.WeakReference
import com.hengfoxwolf.commonbase.base.util.LogX

class VGVUseVActivity : BaseActivity<ActivityVgvuseVactivityBinding>() {

    private lateinit var mReceiver: VGVReceiver

    override fun getLayoutId() = R.layout.activity_vgvuse_vactivity

    override fun init(savedInstanceState: Bundle?) {
        val mAOA = ArrayObjectAdapter(VGVPresenter(this@VGVUseVActivity))
        mAOA.addAll(0, DataFactoryIp.createDataSet())
        val mIBA = ItemBridgeAdapter(mAOA)
        mBinding.vgvList.apply {
            setNumColumns(3)
            verticalSpacing = 10
            horizontalSpacing = 10
            adapter = mIBA
        }

        mReceiver = VGVReceiver(this)
        val mIntentFilter = IntentFilter()
        mIntentFilter.addAction(ACTION_VGV)
        LocalBroadcastManager
            .getInstance(this)
            .registerReceiver(mReceiver, mIntentFilter)
    }

    override fun onDestroy() {
        super.onDestroy()
        LocalBroadcastManager
            .getInstance(this)
            .unregisterReceiver(mReceiver)
    }

    class VGVReceiver(activity: VGVUseVActivity) : BroadcastReceiver() {
        private val mWeakReference = WeakReference(activity)
        override fun onReceive(context: Context?, intent: Intent?) {
            if (context == null || intent == null) {
                return
            }
            when (intent.action) {
                ACTION_VGV -> {
                    LogX.d(TAG, ACTION_VGV)
                }
            }
        }
    }

    companion object {
        const val TAG = "VGVUseVActivity"
        const val ACTION_VGV = "com.android.fragmentdemo.leanback.vgv"
    }
}